package com.gigi.datageniebackendmaster.config;

import com.gigi.datageniebackendmaster.service.ChartService;
import org.redisson.api.RedissonClient;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.*;

/**
 * 线程池配置类
 *
 * @author Gigi
 * @date 2024/7/29 22:58
 */
@Configuration
public class ThreadPoolExecutorConfig {

    @Bean
    @ConditionalOnBean(RedissonClient.class) // 仅在 RedissonClient 存在时加载此 Bean
    public RejectedExecutionHandler customRejectedExecutionHandler(ChartService chartService) {
        return new CustomRejectedExecutionHandler(chartService); // 使用自定义的拒绝策略
    }

    @Bean
    @ConditionalOnMissingBean(RedissonClient.class) // 仅在 RedissonClient 不存在时加载此 Bean
    public RejectedExecutionHandler defaultRejectedExecutionHandler() {
        return new ThreadPoolExecutor.AbortPolicy(); // 使用默认的拒绝策略
    }

    @Bean
    public ThreadPoolExecutor threadPoolExecutor(RejectedExecutionHandler customRejectedExecutionHandler) {
        // 创建线程工厂
        ThreadFactory threadFactory = new ThreadFactory() {
            private int count = 1;

            @Override
            public Thread newThread(Runnable r) {
                Thread thread = new Thread(r);
                // 设置线程名称
                thread.setName("线程" + count);
                count++;
                return thread;
            }
        };
        // 创建线程池
        return new ThreadPoolExecutor(2, 4, 100, TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(3), threadFactory, customRejectedExecutionHandler);
    }

}

